//
// Console.cpp
// Usage: Console driver
// CreateDate: 2009-06-04
// Author: MaJiuyue
//
#include <stdlib.h>
#include <stdio.h>
#include "Console.h"
#include "const.h"

DECLARE_DRIVER(CConsoleDriver)

u8 CDriver::IRQs_nr = 1;		
u16 CDriver::IRQs[] = { KB_IRQ };
u8 CDriver::ports_nr = 18;
u16 CDriver::ports[] = {
	KBD_DATA, KBD_COMMAND,
	VGA_AC_INDEX, VGA_AC_WRITE, VGA_AC_READ,
	VGA_SEQ_INDEX, VGA_SEQ_DATA, VGA_MISC_READ, VGA_MISC_WRITE, 
	VGA_DAC_READ_INDEX, VGA_DAC_WRITE_INDEX, VGA_DAC_DATA, 
	VGA_CRTC_INDEX, VGA_CRTC_DATA,
	VGA_GC_INDEX, VGA_GC_DATA, VGA_INSTAT_READ
};
bool CDriver::bMapMemory = true;
u32 CDriver::paddr = V_MEM_BASE;
u32 CDriver::vaddr = VIRTUAL_V_MEM_BASE;
u32 CDriver::size = V_MEM_SIZE;


extern "C" int write(int file, char *ptr, int len)
{
	return 0;
}

int CConsoleDriver::InitializeDriver()
{
	struct message msg;

	vga.InitializeDriver();
	kb.InitializeDriver();

	handler[IRP_READ] = (IRP_HANDLER)&CConsoleDriver::doRead;
	handler[IRP_WRITE] = (IRP_HANDLER)&CConsoleDriver::doWrite;

	// Create file '/dev/tty0'
	CreateDevice("tty", 1);

	return 0;
}

void CConsoleDriver::irq_handler(u16 irq)
{
	kb.irq_handler(irq);
}

int CConsoleDriver::Shutdown()
{
	vga.write("Not implement!", 14);
	return 0;
}

bool CConsoleDriver::doRead(RequestPackage *IRP, int *ret)
{
	char * buf = (char *)IRP->GetRequestBuffer();
	*ret = 0;

	for(size_t i=0; i<IRP->GetRequestSize(); i++, buf++)
	{
		if(!kb.kbhit())
			break;

		*buf = (char)kb.getch(1);
		vga.write(buf, 1);
		(*ret)++;
	}

	if(*ret>0)
		return true;
	else
		return false;		
}

bool CConsoleDriver::doWrite(RequestPackage *IRP, int *ret)
{
	char * buf = (char *)IRP->GetRequestBuffer();
	size_t size = IRP->GetRequestSize();

	vga.write(buf, size);
	*ret = size;

	return true;
}


